package com.bsoft.gol.hcs.his.service.impl;

import com.bsoft.gol.hcs.clinical.bean.req.CheckTypeRequest;
import com.bsoft.gol.hcs.clinical.bean.req.QueryCheckItemListReq;
import com.bsoft.gol.hcs.clinical.bean.req.QueryCheckPositionListReq;
import com.bsoft.gol.hcs.clinical.bean.req.QueryMedicalSkillListReq;
import com.bsoft.gol.hcs.clinical.bean.response.*;
import com.bsoft.gol.hcs.clinical.bean.vo.ConsultAskVo;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.annotation.RpcService;
import com.bsoft.gol.hcs.enumcase.CheckEnum;
import hcn.util.BaseResponse;
import hcn.util.ResultCode;
import com.bsoft.gol.hcs.his.service.IMedicalSkillsHisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;
import com.bsoft.gol.hcs.utils.HttpClientUtils;
import org.atag.util.http.KdHttpClientUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:检查检验his服务
 * @Author: zhaorb
 * @Date: 2020/6/4 15:08
 **/
@SsdevService("medicalSkillsHisService")
public class MedicalSkillsHisService implements IMedicalSkillsHisService {

    private final static Logger log = LoggerFactory.getLogger(MedicalSkillsHisService.class);

    /**
     * @Description: 获取检查单项目列表
     * @Author: zhaorb
     * @Date: 2020/6/4 15:24
     **/
    @Override
    @RpcService
    public List<QueryCheckItemListResp> queryCheckItemList(QueryCheckItemListReq request) {
        log.info("=queryCheckItemList-入参=>>>" + request.toString() + "=====");
        try {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(Constants.HIS_PATH_URL + CheckEnum.GET_EXAM_MAJOR_ITEM_LIST.getCode() +
                    "?Sender=PHIS&ExamExecuteOrgId=" + request.getOrganizationId());
            if (CommonUtils.isNotEmpty(request.getExamTypeId())) {
                stringBuffer.append("&ExamTypeCode=" + request.getExamTypeId());
            }
            String get = HttpClientUtils.doGet(stringBuffer.toString());
            JSONObject jsonObject = JSONObject.parseObject(get);
            if (jsonObject.getInteger("Code") == ResultCode.SUCCESS && jsonObject.containsKey("Data") &&
                    jsonObject.get("Data") != null) {
                List<QueryCheckItemListRespTemp> list = JSONObject.parseArray(
                        jsonObject.getJSONArray("Data").toJSONString(), QueryCheckItemListRespTemp.class);
                List<QueryCheckItemListResp> checks = new ArrayList<>();
                CheckTypeRequest ct = new CheckTypeRequest();
                ct.setOrganizationId(request.getOrganizationId());
                List<CheckTypeResponse> cts = queryCheckTypeList(ct).getData().getList();
                List<CheckTypeResponse> resCts = new ArrayList<>();
                if (CommonUtils.isNotEmpty(request.getExamTypeId())) {
                    resCts = cts.stream()
                            .filter(ctr -> request.getExamTypeId().equals(ctr.getExamTypeId()))
                            .collect(Collectors.toList());
                }else{
                    resCts.addAll(cts);
                }
                if (CommonUtils.isNotEmpty(resCts)) {
                    CheckTypeResponse typeResponse = resCts.get(0);
                    for (QueryCheckItemListRespTemp temp : list) {
                        QueryCheckItemListResp response = new QueryCheckItemListResp();
                        response.setExamMajorItemId(temp.getExamMajorItemCode());
                        response.setPyCode(temp.getPyCode());
                        response.setExamMajorItemName(temp.getExamMajorItemName());
                        response.setExecuteDepartmentId(temp.getExecuteDepartmentId());
                        response.setExecuteDepartmentName(temp.getExecuteDepartmentName());
                        response.setOrganizationId(typeResponse.getOrganizationId());
                        response.setOrganizationName(typeResponse.getOrganizationName());
                        response.setExamTypeId(typeResponse.getExamTypeId());
                        response.setExamTypeName(typeResponse.getExamTypeName());
                        checks.add(response);
                    }
                }

                return checks;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
//        List<QueryCheckItemListResp> result = new ArrayList<>();
//        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
//        jsonParams.remove("consultId");
//        JSONObject jsonObject = KdHttpClientUtil.doMainPost(Constants.HIS_CLIENT_URL_01
//                , new Object[]{Constants.QUERY_CHECK_ITEM_LIST, "","",jsonParams});
//        log.info("AntibacterialServiceImpl.queryCheckItemList:{}", result);
//        try {
//            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
//                    jsonObject.get("data") != null && !jsonObject.getJSONArray("data").isEmpty()) {
//                result = JSONObject.parseArray(
//                        jsonObject.getJSONArray("data").toJSONString(), QueryCheckItemListResp.class);
//            }
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }


//        log.info("=入参=>>>" + request.toString() + "=====");
//        String jsonContext = JSONDateUtil.readFile("queryCheckItemList");
//        List<QueryCheckItemListResp> list = JSONArray.parseArray(jsonContext, QueryCheckItemListResp.class);
//        return list;
    }
    /**
     * @Description: 获取项目部位和方法（HIS）
     * @Author: xuxy
     * @Date: 2020/6/4 16:12
     **/
    @Override
    @RpcService
    public List<QueryCheckPositionItemResp> queryCheckPositionList(QueryCheckPositionListReq request) {
        log.info("=queryCheckPositionList-入参=>>>" + request.toString() + "=====");
        List<QueryCheckPositionItemResp> resps = new ArrayList<>();
        try {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(Constants.HIS_PATH_URL + CheckEnum.GET_EXAM_ITEM_LIST.getCode() +
                    "?Sender=PHIS&ExamExecuteOrgId=" + request.getOrganizationId());
            if (CommonUtils.isNotEmpty(request.getExamTypeId())){
                stringBuffer.append("&ExamTypeCode=" + request.getExamTypeId());
            }
            if (CommonUtils.isNotEmpty(request.getExamMajorItemId())){
                stringBuffer.append("&ExamMajorItemCode=" + request.getExamMajorItemId());
            }
            String get = HttpClientUtils.doGet(stringBuffer.toString());
            JSONObject jsonObject = JSONObject.parseObject(get);
            if (jsonObject.getInteger("Code") == ResultCode.SUCCESS && jsonObject.containsKey("Data") &&
                    jsonObject.get("Data") != null) {
                List<QueryCheckPositionItemRespTemp> list = JSONObject.parseArray(
                        jsonObject.getJSONArray("Data").toJSONString(), QueryCheckPositionItemRespTemp.class);
                if (CommonUtils.isNotEmpty(list)) {
                    for (QueryCheckPositionItemRespTemp temp : list) {
                        QueryCheckPositionItemResp resp = new QueryCheckPositionItemResp();
                        BeanUtils.copyProperties(temp, resp);
                        resp.setExamItemId(temp.getExamItemCode());
                        List<QueryCheckExamMethodsRespTemp> methods = temp.getExamMethods();
                        List<QueryCheckExamMethodsResp> examMethodsResps = new ArrayList<>();
                        if (CommonUtils.isNotEmpty(methods)) {
                            for (QueryCheckExamMethodsRespTemp respTemp : methods) {
                                QueryCheckExamMethodsResp examMethodsResp = new QueryCheckExamMethodsResp();
                                examMethodsResp.setExamMethodId(respTemp.getExamMethodCode());
                                examMethodsResp.setExamMethodName(respTemp.getExamMethodName());
                                examMethodsResps.add(examMethodsResp);
                            }
                        }
                        resp.setExamMethods(examMethodsResps);
                        resps.add(resp);

                    }
                }
            }
            return resps;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    @RpcService
    public BaseResponse<ConsultAskVo> getHcnConsultAsk(QueryMedicalSkillListReq request) {
        BaseResponse<ConsultAskVo> result = new BaseResponse();
        ConsultAskVo vo;
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        jsonParams.remove("bussType");
        jsonParams.remove("status");
        log.info(System.getProperty("java.class.path")+" "+jsonParams.toString());
        String url= Constants.GOL_CLIENT_URL + Constants.GET_HCN_CONSULT_ASK;
        String str = KdHttpClientUtil.doPost(url, jsonParams.toString(),null);
        JSONObject jsonObject = JSONObject.parseObject(str);
        log.info("url:{}", Constants.GOL_CLIENT_URL + Constants.GET_HCN_CONSULT_ASK);
        log.info("str:{}", str);
        log.info("queryCheckPositionList:{}", result);
        try {
            if (CommonUtils.isNotEmpty(jsonObject)) {
                vo = JSONObject.parseObject(jsonObject.toString(), ConsultAskVo.class);
                result.setData(vo);
                result.setCode(ResultCode.SUCCESS);
            } else {
                result.setCode(ResultCode.ERROR);
                result.setMessage("获取问诊信息失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }
        return result;
    }
    /**
     * @Description: 获取检查类型
     * @Author: zhaorb
     * @Date: 2020/6/4 15:24
     **/
    @Override
    @RpcService
    public BaseResponse<CheckTypeTotalResponse> queryCheckTypeList(CheckTypeRequest request) {
        log.info("=queryCheckTypeList-入参=>>>" + request.toString() + "=====");
        BaseResponse<CheckTypeTotalResponse> result = new BaseResponse();
        CheckTypeTotalResponse checkTypeTotalResponse = new CheckTypeTotalResponse();
        try {
            String get = HttpClientUtils.doGet(Constants.HIS_PATH_URL + CheckEnum.GET_EXAM_TYPE_LIST.getCode() +
                    "?Sender=PHIS&ExamExecuteOrgId=" + request.getOrganizationId());
            JSONObject jsonObject = JSONObject.parseObject(get);
            if (jsonObject.getInteger("Code") == ResultCode.SUCCESS && jsonObject.containsKey("Data") &&
                    jsonObject.get("Data") != null) {
                //出参转换开始
                List<CheckTypeResponseTemp> list = JSONObject.parseArray(
                        jsonObject.getJSONArray("Data").toJSONString(), CheckTypeResponseTemp.class);
                //出参转换结束
                checkTypeTotalResponse.setTotal(list.size());
                List<CheckTypeResponse> checks = new ArrayList<>();
                List<OrganizeListResponse> organizeList = getOrganizeList().getData();
                List<OrganizeListResponse> filter = organizeList.stream()
                        .filter(organize -> request.getOrganizationId().equals(organize.getOrganizationId()))
                        .collect(Collectors.toList());
                if (CommonUtils.isNotEmpty(filter)) {
                    OrganizeListResponse organize = filter.get(0);
                    for (CheckTypeResponseTemp temp : list) {
                        CheckTypeResponse response = new CheckTypeResponse();
                        response.setExamTypeId(temp.getExamTypeCode());
                        response.setPyCode(temp.getPyCode());
                        response.setExamTypeName(temp.getExamTypeName());
                        response.setOrganizationId(request.getOrganizationId());
                        response.setOrganizationName(organize.getOrganizationName());
                        checks.add(response);
                    }

                }
                checkTypeTotalResponse.setList(checks);
                result.setData(checkTypeTotalResponse);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }
        return result;


//        log.info("=queryCheckTypeList-入参=>>>" + request.toString() + "=====");
//        BaseResponse<CheckTypeTotalResponse> result = new BaseResponse();
//        CheckTypeTotalResponse checkTypeTotalResponse = new CheckTypeTotalResponse();
//        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
//        JSONObject jsonObject = KdHttpClientUtil.doMainPost(Constants.HIS_CLIENT_URL_01
//                ,  new Object[]{Constants.QUERY_CHECK_TYPE_LIST, "","", jsonParams});
//        log.info("AntibacterialServiceImpl.listAntibacterial第三方返回数据:{}", result);
//        try {
//            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
//                    jsonObject.get("data") != null && !jsonObject.getJSONArray("data").isEmpty()) {
//                //出参转换开始
//                List<CheckTypeResponse> list = JSONObject.parseArray(
//                        jsonObject.getJSONArray("data").toJSONString(), CheckTypeResponse.class);
//                //出参转换结束
//                checkTypeTotalResponse.setTotal(list.size());
//                checkTypeTotalResponse.setList(list);
//                result.setData(checkTypeTotalResponse);
//            } else {
//                result.setCode(jsonObject.getInteger("code"));
//                result.setMessage(jsonObject.getString("message"));
//            }
//        } catch (JSONException e) {
//            e.printStackTrace();
//            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
//            result.setCode(Constants.ERR_CODE);
//        }
//        return result;

//        BaseResponse<CheckTypeTotalResponse> result = new BaseResponse();
//        log.info("=入参=>>>" + request.toString() + "=====");
//        String jsonContext = JSONDateUtil.readFile("checkType");
//        try {
//            String xml = JsonToXmlUtil.jsonToPrettyXml(JSONObject.parseObject(jsonContext));
//            JSONObject json = JsonToXmlUtil.xmlToJson(xml);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        CheckTypeTotalResponse list = JSONArray.parseObject(jsonContext, CheckTypeTotalResponse.class);
//        result.setData(list);
//        return result;
    }
    /**
     * @Description: 获得检查机构列表
     * @Author: zhaorb
     * @Date: 2020/9/3 15:24
     **/
    @Override
    @RpcService
    public BaseResponse<List<OrganizeListResponse>> getOrganizeList() {
        List<OrganizeListResponse> organizeList = new ArrayList<>();
        BaseResponse result = new BaseResponse();
        try {
            String get = HttpClientUtils.doGet(Constants.HIS_PATH_URL + CheckEnum.GET_ORGANIZE_LIST.getCode() + "?Sender=PHIS");
            JSONObject jsonObject = JSONObject.parseObject(get);
            if (jsonObject.getInteger("Code") == ResultCode.SUCCESS && jsonObject.containsKey("Data") &&
                    jsonObject.get("Data") != null) {
                List<OrganizionResponse> list = JSONObject.parseArray(
                        jsonObject.get("Data").toString(), OrganizionResponse.class);
                for (OrganizionResponse organizion : list) {
                    OrganizeListResponse ol = new OrganizeListResponse();
                    ol.setOrganizationId(organizion.getExamExecuteOrgId());
                    ol.setOrganizationName(organizion.getExamExecuteOrgName());
                    organizeList.add(ol);
                }
                result.setData(organizeList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }
        return result;
    }
}
